package com.zhou.common.base.mq.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

public class TraceFilter extends GenericFilterBean {

    private static final String traceId="traceId";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
    }

    private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String traceId = request.getHeader("traceId");
        if (StringUtils.isBlank(traceId)){
            MDC.put(TraceFilter.traceId, UUID.randomUUID().toString().replace("-", ""));
        }else {
            MDC.put(TraceFilter.traceId, traceId);
        }
        response.addHeader(TraceFilter.traceId, MDC.get(TraceFilter.traceId));

        chain.doFilter(request, response);
        MDC.clear();
    }

}
